import * as React from "react";
import {Button, Table, Tag, Space, message, Tooltip, Popconfirm, Pagination} from 'antd';
import { PlusOutlined, DeleteOutlined, SyncOutlined } from '@ant-design/icons';
import './index.less'
import ArticleAdd from "./add";
import ArticleView from "./view";
import {ArticlePages, DelArticle} from "../../../api/admin/article";
import {timeFormat} from "../../../utils/timeUtils";
import {CategoryAll} from "../../../api/admin/category";
import {ArticleUpload} from "../../../api/admin/article";
import {RandomColor} from "../../../utils/colorUtils";


export default class AdminArticle extends React.Component{
	
	state = {
		dataRequest: {
			page: 1,
			limit: 10,
			startTIme: '',
			endTime: '',
			title: ''
		},
		resultData: {
			total: 0,
			pageTotal: 0,
			data: [],
		},
		category: [],
		data: [
			{
				key: '1',
				name: 'John Brown',
				age: 32,
				address: 'New York No. 1 Lake Park',
				tags: ['nice', 'developer'],
			},
			{
				key: '2',
				name: 'Jim Green',
				age: 42,
				address: 'London No. 1 Lake Park',
				tags: ['loser'],
			},
			{
				key: '3',
				name: 'Joe Black',
				age: 32,
				address: 'Sidney No. 1 Lake Park',
				tags: ['cool', 'teacher'],
			},
		],
		addFlag: false,
		viewFlag: false,
		viewItem: '',
		selectRowKeys: []
	}


	componentDidMount() {
		this.loadArticleData({...this.state.dataRequest})
		this.loadCategoryData()
	}

	loadArticleData = (params) => {
		ArticlePages(params).then(res => {
			if (res.code === '001001200') {
				const {data, total, pageTotal} = res.data
				this.setState({resultData: {data, total, pageTotal}})
			} else {
				message.error("获取数据失败")
			}
		}).catch(err => {
			message.error("获取数据失败")
		})
	}

	loadCategoryData = () => {
		CategoryAll().then(res => {
			console.log("loadCategoryData", res);
			if (res.code === '001001200') {
				this.setState({category: res.data})
			} else {
				message.error("获取数据失败")
			}
		}).catch(err => {
			message.error("获取数据失败")
		})
	}

	/**
	 * 修改页大小
	 * @param page
	 * @param pageSize
	 */
	onChangeHandler = (page, pageSize) => {
		console.log("修改页大小 => onChangeHandler：", page, pageSize)
		const {dataRequest} = this.state;
		const newParams = {...dataRequest, page: page, limit: pageSize};
		this.setState({dataRequest: newParams})
		this.loadArticleData(newParams)
	}


	/**
	 * 保存文章
	 * @param data
	 */
	saveArticle = (data) => {
		this.setState({addFlag: false})
		console.log("saveArticle", data);
		let formData = new FormData();
		Object.keys(data).forEach(item => {
			formData.append(item, data[item])
		})
		ArticleUpload(formData).then(res => {
			console.log(res);
			if (res.code === '001001200') {
				this.loadArticleData()
				message.success("上传文章成功")
			} else {
				message.error("上传文章失败")
			}
		}).catch(err => {
			console.log(err);
		})
		
	}

	/**
	 * 打开预览窗口
	 * @param data
	 */
	openView = (data) => {
		console.log("openView", data)
		this.setState({viewItem: data.markdown, viewFlag: true})
	}

	/**
	 * 删除文章
	 * @param ids
	 */
	articleDelete = (ids) => {
		DelArticle({ids: ids}).then(res => {
			if (res.code === '001001200') {
				this.loadArticleData()
				message.success("删除文章成功")
			} else {
				message.error("删除文章失败")
			}
		}).catch(err => {
			message.error("删除文章失败")
		})
	}

	/**
	 * 多选数据
	 * @param ids
	 */
	selectRowsHandler = (ids) => {
		this.setState({selectRowKeys: ids})
	}

	/**
	 * 批量删除
	 */
	articleBatchDel = () => {
		const {selectRowKeys} = this.state;
		if (selectRowKeys.length <= 0) {
			message.warn("未选中数据，删除失败")
		} else {
			this.articleDelete(selectRowKeys.join("-"))
		}
	}

	closeModel = (flag) => {
		this.setState({addFlag: false})
	}

	closeViewModel = () => {
		this.setState({viewFlag: false})
	}

	render() {

		const {data, total} = this.state.resultData
		const {page, limit} = this.state.dataRequest

		const categoryName = (id) => {
			console.log("categoryName", id)
			let ids = id.split(",");
			let newList = this.state.category.filter(item => ids.includes(item.id + ''));
			if (newList.length <= 0) {
				return "暂无分类";
			} else {
				return newList.map(item => item.title);
			}
		}

		const columns = [
			{
				title: '文章标题',
				dataIndex: 'title',
				key: 'title',
				width: '15%',
				render: text => (<a href="#">{text}</a>),
				ellipsis: true,
			},
			{
				title: '简介',
				dataIndex: 'synopsis',
				key: 'synopsis',
				width: '15%',
				render: text => (
					<Tooltip placement="topLeft" title={text}>
						{text}
					</Tooltip>
				),
				ellipsis: true,
			},
			{
				title: '创建时间',
				dataIndex: 'createTime',
				key: 'createTime',
				width: '7%',
				render: createTime => (
					<div>
						{timeFormat(createTime)}
					</div>
				)
			},
			{
				title: '文章分类',
				dataIndex: 'cateList',
				key: 'cateList',
				width: '16%',
				render: (cateList, recode) => (
					<>
						{
							categoryName(cateList).map(tag => {
								return (
									<Tag style={{borderRadius: 5 + 'px'}} color={RandomColor()} key={tag}>
										{tag.toUpperCase()}
									</Tag>
								);
							})
						}
					</>
				)
			},
			{
				title: '文章草稿',
				dataIndex: 'artDraft',
				key: 'artDraft',
				width: '6%',
				render: artDraft => (
					artDraft ? <div>草稿</div> : <div>正式发布</div>
				)
			},
			{
				title: '文章标签',
				key: 'tags',
				dataIndex: 'tags',
				width: '21%',
				render: tags => (
					<>
						{tags.split(",").map(tag => {
							return (
								<Tag style={{borderRadius: 5 + 'px'}} color={RandomColor()} key={tag}>
									{tag.toUpperCase()}
								</Tag>
							);
						})}
					</>
				),
			},
			{
				title: '操作',
				key: 'action',
				width: '20%',
				render: (_, record) => (
					<Space size="small">
						<Button
							type="primary"
							size="small"
							onClick={() => this.openView(record)}
							style={{backgroundColor: '#7cb305', borderColor: '#7cb305'}}>预览</Button>
						<Button type="primary" size="small">数据</Button>
						<Button type="primary" size="small" style={{backgroundColor: '#ff7a45', borderColor: '#ff7a45'}}>修改</Button>
						<Popconfirm
							placement="bottomRight"
							title="确认删除这篇文章"
							onConfirm={() => this.articleDelete(record.id)}
							okText="删除"
							cancelText="在想想"
						>
							<Button type="primary" size="small" danger>删除</Button>
						</Popconfirm>
					</Space>
				),
			},
		];


		return (
			<div className="container_area">
				<div className="top_tools">
					<Button
						size="small"
						onClick={() => {this.setState({addFlag: true})}}
						type="primary"
						icon={<PlusOutlined />}
						style={{marginRight: 1 + 'rem'}}>增加</Button>
					<Popconfirm
						placement="bottomLeft"
						title="确认删除选中的文章"
						onConfirm={this.articleBatchDel}
						okText="确认删除"
						cancelText="在想想"
					>
						<Button
							size="small"
							type="primary"
							icon={<DeleteOutlined />} style={{marginRight: 1 + 'rem'}}
							danger>删除</Button>
					</Popconfirm>
					<Button
						size="small"
						type="primary"
						onClick={() => this.loadArticleData()}
						style={{backgroundColor: '#389e0d'}}
						icon={<SyncOutlined  />}>刷新</Button>
				</div>
				<ArticleAdd
					category={this.state.category}
					handleOk={data => this.saveArticle(data)}
					handleCancel={this.closeModel}
					flag={this.state.addFlag}
				/>
				<Table
					rowSelection={{
						type: 'checkbox',
						onChange:  (selectedRowKeys, selectedRows) => this.selectRowsHandler(selectedRowKeys)
					}}
					rowKey={record => record.id}
					style={{marginTop: 1 + 'rem'}}
					size="middle"
					bordered
					pagination={{
						onChange: (page, pageSize) => this.onChangeHandler(page, pageSize),
						showSizeChanger: true,
						showQuickJumper: false,
						defaultCurrent: 1,
						defaultPageSize: 10,
						current: page,
						pageSize: limit,
						total: total,
						showTotal: () => `共 ${total} 页`
					}}
					columns={columns}
					dataSource={data} />
				<ArticleView
					handleCancel={this.closeViewModel}
					content={this.state.viewItem}
					flag={this.state.viewFlag} />

			</div>
			
		)
	}
}